package com.ref.entity;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author wzm
 * @create 2023-02-14 10:08
 */
//测试反射获创建对象
public class ReflectTest3 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
     //获取空参构造方法并创建对象
        //获取字节码文件对象
        Class clazz = Class.forName("com.ref.entity.Student");
        //获取空参构造方法
        Constructor con = clazz.getConstructor();
        //调用创建对象的方法
         Student student = (Student) con.newInstance();
        System.out.println("student = " + student);

        System.out.println("-----------------------------------------");

        //获取有参构造函数
        Constructor con2 = clazz.getDeclaredConstructor(String.class, int.class);

        //临时修改构造方法的访问权限 暴力反射
        con2.setAccessible(true);

        //创建对象需要传入构造方法所需的参数
        Student student1 = (Student) con2.newInstance("zs",18);
        System.out.println("student1 = " + student1);


    }
}
